//index.js
const util = require('../../utils/util.js');
const pageUtil = require('../../utils/page.js');
const app = getApp();

function getAccount(callback) {
  wx.request({
    url: app.processUri('accounts/_'),
    method: "GET",
    header: { 'Authorization': app.globalData.accessToken },
    success: function (res) {
      callback(res.data);
    },
  });
}
var count = 0;
Page({
  data: {
    stars: [0, 1, 2, 3, 4],
    normalSrc: '../../images/no-star.png',
    selectedSrc: '../../images/full-star.png',
    halfSrc: '../../images/half-star.png',
    key: 0,//评分
    drawingPicture: false,
    playIconClass: 'icon-sound',
    cardAnimationData: '',
    userAnimationData: '',
    buttonAnimationData: '',
    tipsAnimationData: '',
    currentDate: util.formatDate(new Date(), false, true),
    contentFontSize: 120,
    customDateLabel: '',
    theDateLabel: '',
    theDateDiscription: '',
    inputAssess: false,
    recording: false,
    recordCancelling: false,
    previewMode: false,
    recordingSeconds: 0,
    cardImage: '',
    avatarImage: '',
    festivalNames: [],
    festivalIndex: 0,
    sentenceTexts: [],
    sentenceIndex: 0,
  },

  logining: false,
  recordingSecondsIntervalId: null,
  playingAnimationIntervalId: 0,
  playingAnimationIndex: 0,
  cardImagePath: '',
  cardImageSize: 0,
  recordingAudioPath: '',
  committed: false,
  festivals: [],
  sentences: [],
  resources: null,
  selectedSentence: null,
  selectedFestival: null,
  selectedResource: null,
  fetchFestivalTime: 0,
  playingMillis: 0,
  playIconClasses: ['icon-sound', 'icon-sound_low', 'icon-sound_mid'],

  onLoad: function (options) {
    this.tipsAnimation = wx.createAnimation({
      duration: 500,
      delay: 400
    });
    this.cardAnimation = wx.createAnimation({ duration: 200 });
    this.userAnimation = wx.createAnimation({ duration: 500 });
    this.buttonAnimation = wx.createAnimation({ duration: 500 });
  },

  onReady: function () {
    // this.startLogin();
    app.changeStyle(this);
    this.resetPage();
  },

  startLogin: function () {
    const page = this;
    pageUtil.startLoading(page);
    page.logining = true;
    app.loadUserInfo((info) => {
      if (info != null) {
        page.setData({ avatarImage: info.avatarUrl });
        app.refreshAccessToken(() => {
          page.logining = false;
          pageUtil.stopLoading(page);
          page.refreshDate(page.fetchFestivalTime == 0);
        });
      } else {
        wx.showModal({
          title: '错误',
          content: '无法获取用户信息，点击重试',
          showCancel: false,
          complete: () => {
            page.startLogin();
          }
        });
      }
    });
  },

  onShow: function () {
    const page = this;
    if (util.currentTime() - page.fetchFestivalTime > 60000) page.refreshDate();
    getAccount((account) => {
      page.accountUpdateTime = account.modifyTime;
      page.setData({ hasAccountChange: page.accountUpdateTime > app.globalData.accountUpdateTime });
    });
  },

  onHide: function () {
    wx.stopVoice();
    if (this.committed) {
      this.committed = false;
      this.resetPage()
    }
  },

  refreshDate: function (forceData) {
    const page = this;
    const newDate = util.formatDate(new Date(), false, true);
    if (page.data.currentDate != newDate) {
      page.setData({ currentDate: newDate });
      page.fetchFestivals();
    } else if (forceData == true) {
      page.fetchFestivals();
    }
  },

  setFestival: function (festival) {
    this.selectedFestival = festival;
    app.changeStyle(this, festival);
    this.resources = null;
    if (festival != null) {
      this.setData({ theDateLabel: festival['name'] });
      this.fetchSentence(festival.id);
    } else this.fetchSentence(0);
  },

  fetchFestivals: function () {
    const page = this;
    page.fetchFestivalTime = 0;
    if (app.globalData.accessToken == null || app.globalData.accessToken == '') {
      return;
    }
    const requestToken = app.globalData.accessToken;
    pageUtil.startLoading(page);
    wx.request({
      url: app.processUri('festivals?millis=' + (new Date()).getTime()),
      method: "GET",
      header: { 'Authorization': requestToken },
      success: (res) => {
        page.fetchFestivalTime = util.currentTime();
        if (res.statusCode == 401) {
          if (page.logining) {
            page.fetchFestivalTime = 0;
          } else if (requestToken != app.globalData.accessToken) page.fetchFestivals();
        } else if (res.data.length > 0) {
          page.festivals = res.data;
          const festivalNames = [];
          page.festivals.forEach(res => {
            let name = res['name'];
            if (name == null || name == '') name = util.formatChineseDate(res.month, res.day);
            res['name'] = name;
            festivalNames.push(name);
          });
          page.setData({
            festivalNames: festivalNames,
            festivalIndex: 0
          });
          page.setFestival(page.festivals[0]);
        }
      },
      complete: () => { pageUtil.stopLoading(page) }
    })
  },

  fetchSentence: function (id) {
    const page = this;
    wx.request({
      url: app.processUri('festivals', id, 'sentences/random'),
      method: "GET",
      header: { 'Authorization': app.globalData.accessToken },
      success: function (res) {
        if (res.statusCode == 401) {
          wx.showToast({ title: '已在其他位置登录，当前登录已过期。请重新进入' });
        } else {
          page.sentences = res.data;
          const sentenceTexts = [];
          page.sentences.forEach(res => { sentenceTexts.push(res.text) });
          page.setData({
            sentenceTexts: sentenceTexts,
            sentenceIndex: 0
          });
          page.selectSentence(page.sentences[0]);
        }
      }
    });
  },

  selectSentence: function (sentence) {
    this.selectedSentence = sentence;
    let discription = '';
    if (sentence != null) { discription = sentence.text; }
    this.setData({ theDateDiscription: discription });
  },

  inputingText: function (res) {
    let text = res.detail.value;
    const textLength = util.chineseStringLength(text);
    if (textLength > app.globalData.maxLabelSize) {
      text = text.substring(0, util.chineseStringLengthIndex(text, app.globalData.maxLabelSize));
    }
    this.refreshLabelTextSize(text);
    return text;
  },

  refreshLabelTextSize: function (text) {
    const newSize = util.computeFontSize(text);
    if (newSize != this.data.contentFontSize) {
      this.setData({
        contentFontSize: newSize
      });
    }
  },

  cancelPost: function (event) {
    wx.stopVoice();
    this.resetPage();
  },

  commitPost: function (event) {
    const page = this;
    let title = page.data.customDateLabel;
    if (title == null || title == '') title = page.data.theDateLabel;
    let sid = 0, style = '', param = '';
    if (page.selectedSentence != null) {
      sid = page.selectedSentence.id
      style = page.selectedFestival['style'];
    }
    wx.showLoading({ title: '发布中...' });
    const commits = {
      title: title, duration: page.data.recordingSeconds, sentenceId: sid, style: style
    };
    const uploads = [
      {
        path: page.recordingAudioPath,
        name: page.data.recordingSeconds
      }];
    if (page.selectedResource != null) {
      commits.resources = [{
        id: page.selectedResource.id,
        param: JSON.stringify(page.selectedResource.param)
      }];
    } else {
      uploads.push(
        {
          path: page.cardImagePath,
          name: page.data.theDateLabel
        }
      )
    }
    createPost(commits, uploads, function (postId) {
      wx.navigateTo({ url: event.currentTarget.dataset.navigatePath + '?postId=' + postId });
      page.committed = true;
      wx.hideLoading();
    });
  },

  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '今天是' + this.data.theDateLabel + ',说句祝福让亲友打赏吧!',
      path: '',
      imageUrl: 'http://brickhu.qiniudn.com/share_picture.png',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  onRecordButtonTouchStart: function (e) {
    const page = this;
    if (!page.data.recording) {
      wx.createSelectorQuery().select('#recordButton').boundingClientRect(function (rect) { page.recordButtonRect = rect; }).exec()
      page.startRecord();
    }
  },

  onRecordButtonTouchMove: function (e) {
    if (this.data.recording) {
      const y = e.touches[0].pageY;
      const cancel = y < this.recordButtonRect.top;
      if (this.data.recordCancelling != cancel) {
        this.setData({ recordCancelling: cancel });
      }
    }
  },

  //录音交互
  startRecord: function () {
    const page = this;
    if (page.data.recording || page.recordingSecondsIntervalId != null) return;
    page.setData({
      recording: true,
      recordingSeconds: 0
    });
    setTimeout(() => {
      wx.startRecord({
        success: (res) => {
          if (!page.data.recordCancelling) {
            page.recordingAudioPath = res.tempFilePath;
            if (page.data.recordingSeconds >= app.globalData.minRecordSeconds) {
              page.startPreview('语音评价');
            }
          }
        },
        fail: (res) => {
          page.setData({ recordingSeconds: 0 });
        },
        complete: () => {
          page.setData({
            recording: false,
            recordCancelling: false,
          });
          if (page.recordingSecondsIntervalId != null) {
            clearInterval(page.recordingSecondsIntervalId);
            page.recordingSecondsIntervalId = null;
          }
        }
      });
      page.recordingSecondsIntervalId = setInterval(() => {
        page.setData({ recordingSeconds: page.data.recordingSeconds + 1 });
        if (!page.data.recording) {
          wx.stopRecord();
        }
      }, 1000);
    }, 50);
  },

  stopRecord: function () {
    if (this.data.recording) {
      this.setData({ recording: false });
      if (this.data.recordingSeconds > 1) wx.stopRecord();
    }
  },

  cancelRecord: function () {
    if (this.data.recording) {
      let time = this.data.recordingSeconds;
      this.setData({
        recording: false,
        recordingSeconds: 0,
      });
      if (time > 1) wx.stopRecord();
    }
  },

  stopPlayAnimation: function () {
    let page = this;
    clearInterval(page.playingAnimationIntervalId);
    page.playingAnimationIndex = 0;
    page.setData({ playIconClass: page.playIconClasses[0] });
  },

  playOrStopRecord: function () {
    let page = this;
    let millis = 200;
    page.stopPlayAnimation();
    wx.stopVoice();
    if (page.playingMillis > 0) {
      page.playingMillis = 0;
    } else {
      page.playingMillis = page.data.recordingSeconds * 1000;
      page.playingAnimationIntervalId = setInterval(function () {
        if (page.playingMillis <= 0) {
          page.stopPlayAnimation();
        } else {
          page.playingMillis = Math.max(0, page.playingMillis - millis);
          page.playingAnimationIndex = (page.playingAnimationIndex + 1) % page.playIconClasses.length;
          page.setData({
            playIconClass: page.playIconClasses[page.playingAnimationIndex]
          });
        }
      }, millis);
      wx.playVoice({ filePath: this.recordingAudioPath });
    }
  },

  resetPage: function () {
    const page = this;
    page.refreshDate();
    wx.setNavigationBarTitle({ title: '评价' });
    page.setData({
      customDateLabel: '',
      cardImage: '',
      recording: false,
      previewMode: false
    });
    page.userAnimation.translateY(-300).opacity(0).step()
    page.cardAnimation.translateY(300).scale(0).opacity(0).step()
    page.buttonAnimation.translateY(300).opacity(0).step()
    page.tipsAnimation.opacity(0).step()
    page.setData({
      userAnimationData: page.userAnimation.export(),
      cardAnimationData: page.cardAnimation.export(),
      buttonAnimationData: page.buttonAnimation.export(),
      tipsAnimationData: page.tipsAnimation.export()
    });
  },

  startPreview: function (title) {
    const page = this;
    page.refreshLabelTextSize();
    wx.setNavigationBarTitle({ title: title });
    if (title === '输入评价') {
      page.setData({
        inputAssess: true
      });
    } else if (title === '语音评价') {
      page.setData({
        inputAssess: false
      });
    }
    page.setData({
      // avatarImage: app.globalData.userInfo.avatarUrl,
      previewMode: true
    });
    page.userAnimation.translateY(0).opacity(1).step()
    page.cardAnimation.translateY(0).scale(1).opacity(1).step()
    page.buttonAnimation.translateY(0).opacity(1).step()
    page.tipsAnimation.opacity(1).step()
    page.setData({
      userAnimationData: page.userAnimation.export(),
      cardAnimationData: page.cardAnimation.export(),
      buttonAnimationData: page.buttonAnimation.export(),
      tipsAnimationData: page.tipsAnimation.export()
    });
    if (page.resources == null) {
      wx.request({
        url: app.processUri('festivals', page.selectedFestival.id, 'resources'),
        method: "GET",
        header: { 'Authorization': app.globalData.accessToken },
        success: function (res) {
          if (res.statusCode == 401) {
            wx.showToast({ title: '已在其他位置登录，当前登录已过期。请重新进入' });
          } else {
            page.resources = res.data;
          }
        }
      });
    }
    setTimeout(() => {
      page.playOrStopRecord();
    }, 50);
  },
  // 输入评价
  inputAssess: function (e) {
    const page = this;
    this.startPreview('输入评价');
    page.setData({
      customDateLabel: e.detail.value
    })
  },
  //点击左边,半颗星
  selectLeft: function (e) {
    var key = e.currentTarget.dataset.key
    if (this.data.key == 0.5 && e.currentTarget.dataset.key == 0.5) {
      //只有一颗星的时候,再次点击,变为0颗
      key = 0;
    }
    count = key
    this.setData({
      key: key
    })
  },
  //点击右边,整颗星
  selectRight: function (e) {
    var key = e.currentTarget.dataset.key
    count = key
    this.setData({
      key: key
    })
  },
  startRating: function (e) {
    wx.showModal({
      title: '分数',
      content: "" + count,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    })
  }

})

wx.showShareMenu({
  withShareTicket: true
})